package com.cmii.sjw.department.control.jsc.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cmii.sjw.department.control.jsc.mapper.*;
import com.cmii.sjw.department.control.jsc.model.RoleCockpit;
import com.cmii.sjw.department.control.jsc.model.entity.CockpitMetricsTree;
import com.cmii.sjw.department.control.jsc.service.RoleCockpitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author lizheng
 * @Date 2025-05-13 周二 11:20
 * @Version 1.0
 */
@Service
public class RoleCockpitServiceImpl extends ServiceImpl<RoleCockpitMapper, RoleCockpit> implements RoleCockpitService {

    @Autowired
    private RoleCockpitMapper roleCockpitMapper;

    @Autowired
    private CockpitMetricsTreeMapper cockpitMetricsTreeMapper;

    @Override
    public List<CockpitMetricsTree> getCockpitListByRole(Long roleId) {
        List<Long> cockpitIds = roleCockpitMapper.selectList(
                new LambdaQueryWrapper<RoleCockpit>()
                        .eq(RoleCockpit::getRoleId, roleId)
        ).stream().map(RoleCockpit::getCockpitId).collect(Collectors.toList());

        if (cockpitIds.isEmpty()) return Collections.emptyList();

        return cockpitMetricsTreeMapper.selectBatchIds(cockpitIds);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdateRoleCockpits(Long roleId, List<Long> cockpitIds) {
        // 1. 删除原有指标权限
        remove(new LambdaQueryWrapper<RoleCockpit>().eq(RoleCockpit::getRoleId, roleId));

        // 2. 如果新数据不为空，则批量插入
        if (CollUtil.isNotEmpty(cockpitIds)) {
            List<RoleCockpit> list = cockpitIds.stream().map(cockpitId ->
                    new RoleCockpit()
                            .setRoleId(roleId)
                            .setCockpitId(cockpitId)
                            .setCreateTime(new Date())
            ).collect(Collectors.toList());

            saveBatch(list);
        }
    }

    @Override
    public void deleteRoleCockpit(Long roleId) {
        roleCockpitMapper.delete(new LambdaQueryWrapper<RoleCockpit>()
                .eq(RoleCockpit::getRoleId, roleId));
    }

    @Override
    public List<Long> getCockpitIdsByRole(Long roleId) {
        return roleCockpitMapper.selectList(
                        new LambdaQueryWrapper<RoleCockpit>()
                                .eq(RoleCockpit::getRoleId, roleId)
                ).stream()
                .map(RoleCockpit::getCockpitId)
                .collect(Collectors.toList());
    }
}
